// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    // 从数据库中获取商品数据
    const productsCollection = db.collection('products')
    
    // 根据参数获取不同类型的商品
    const { type, limit = 10 } = event
    
    let query = productsCollection
    
    // 根据类型筛选
    if (type === 'hot') {
      query = query.where({
        isHot: true
      })
    } else if (type === 'new') {
      query = query.where({
        isNew: true
      })
    }
    
    // 获取商品数据
    const { data: products } = await query
      .limit(limit)
      .orderBy('order', 'asc')
      .get()
    
    return {
      success: true,
      data: products
    }
  } catch (err) {
    return {
      success: false,
      errMsg: err.message
    }
  }
}